type LogLevel = 'info' | 'warn' | 'error' | 'debug';

interface LogMessage {
  timestamp: string;
  level: LogLevel;
  message: string;
  data?: any;
}

class Logger {
  private static instance: Logger;
  private isProduction = import.meta.env.PROD;
  private logQueue: LogMessage[] = [];
  private maxQueueSize = 100;

  private constructor() {
    window.addEventListener('unload', () => {
      this.flush();
    });
  }

  public static getInstance(): Logger {
    if (!Logger.instance) {
      Logger.instance = new Logger();
    }
    return Logger.instance;
  }

  private createLogMessage(level: LogLevel, message: string, data?: any): LogMessage {
    return {
      timestamp: new Date().toISOString(),
      level,
      message,
      data,
    };
  }

  private addToQueue(logMessage: LogMessage) {
    this.logQueue.push(logMessage);
    if (this.logQueue.length >= this.maxQueueSize) {
      this.flush();
    }
  }

  private flush() {
    if (this.logQueue.length === 0) return;

    // 在生产环境中，可以将日志发送到服务器
    if (this.isProduction) {
      // TODO: 实现日志上报逻辑
      // const logsToSend = [...this.logQueue];
      // this.sendToServer(logsToSend);
    }

    this.logQueue = [];
  }

  public info(message: string, data?: any) {
    const logMessage = this.createLogMessage('info', message, data);
    this.addToQueue(logMessage);
    if (!this.isProduction) {
      console.log(`[INFO] ${message}`, data);
    }
  }

  public warn(message: string, data?: any) {
    const logMessage = this.createLogMessage('warn', message, data);
    this.addToQueue(logMessage);
    if (!this.isProduction) {
      console.warn(`[WARN] ${message}`, data);
    }
  }

  public error(message: string, data?: any) {
    const logMessage = this.createLogMessage('error', message, data);
    this.addToQueue(logMessage);
    console.error(`[ERROR] ${message}`, data);
  }

  public debug(message: string, data?: any) {
    if (this.isProduction) return;
    
    const logMessage = this.createLogMessage('debug', message, data);
    this.addToQueue(logMessage);
    console.debug(`[DEBUG] ${message}`, data);
  }
}

export const logger = Logger.getInstance(); 